<template>
  <el-dialog
    v-loading.lock="loading"
    class="base-dialog user-group-dialog"
    :custom-class="'panna-dialog_medium'"
    :title="title"
    :visible.sync="dialogVisible"
    :append-to-body="true"
    :before-close="handleClose"
  >
    <p slot="title">{{ title }}</p>
    <div class="material-search-container">
      <el-row>
        <el-col :span="24">
          <div class="chioseFileDiv">
            <span style="margin-left: 35px">下载报告</span>
            <div style="float: right; margin-right: 45px">
              <el-button
                type="primary"
                icon="el-icon-download"
                @click="downLoad"
                >点击下载</el-button
              >
            </div>
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="24">
          <div class="chioseFileDiv">
            <span style="margin-left: 35px">上传报告</span>
            <div style="float: right; margin-right: 45px">
              <el-button
                slot="trigger"
                size="small"
                type="primary"
                @click="choiseFile()"
                >选取文件</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-paperclip"
                @click="uploadImport"
                >点击上传</el-button
              >
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-upload
            ref="upload"
            :multiple="true"
            action="entrustOrder"
            class="upload-demo"
            :limit="1"
            :accept="accept"
            :on-change="handFileChange"
            :http-request="uploadSectionFile"
            :auto-upload="false"
            :show-file-list="true"
          ></el-upload>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import saverFile from "file-saver";
import { mapGetters } from "vuex";
import { formdataify } from "../../../utils/index";
import htmlDocx from "html-docx-js/dist/html-docx";
import { Get, UpdateReportData } from "../../../api/Report/ReportManage.js";
import { GetStaticFileInfo } from "@/api/Base";
export default {
  name: "ReportStandingBookDialog",
  props: {
    fromSource: {
      type: String,
      default: "",
    },
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    reportId: {
      type: String,
      default: "",
    },
    dataGroup: {
      type: Number,
      default: 0,
    },
    downLoadDisabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      title: "报告上传",
      businessType: 50,
      reportData: [],
      accept: ".doc,.docx",
      loading: false,
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
  },
  created() {
    this.dialogVisible = this.dialogFormVisible;
    // 查询报告数据
    this.init();
  },
  methods: {
    async init() {
      this.loading = true;
      await Get({ id: this.reportId }).then((res) => {
        if (res.code === 200) {
          this.reportData = res.data;
          this.loading = false;
        }
      });
    },

    uploadSectionFile(params) {
      if (this.reportData.reportStatusCode === 20) {
        this.$message({
          message: "审核中的数据不允许上传报告",
          type: "warning",
        });
        return false;
      }

      var file = params.file;
      var isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 10MB!");
        return;
      }
      // 判断上传文件的格式
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "docx";
      const extension2 = testmsg === "doc";
      if (!extension && !extension2) {
        this.$message({
          message: "上传文件只能是doc、docx格式!",
          type: "warning",
        });
        return;
      }
      var formData = new FormData();
      formData.append(file.name, file);
      const obj = {
        businessType: this.businessType,
        file: file,
      };
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form).then((res) => {
        this.reportData.reportUrl = res.data.filePath;
        this.reportData.reportFileName = file.name;
        this.reportData.newReportFileName = res.data.newFileName;
        this.reportData.dataGroup = this.DataGroup;
        UpdateReportData(this.reportData).then((res) => {
          if (res.code === 200) {
            this.handleClose();
          }
        });
      });
    },
    handFileChange() {},
    // 点击上传
    uploadImport() {
      this.$refs.upload.submit();
    },
    // 选取文件
    choiseFile() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    // 下载
    downLoad() {
      if (this.reportData.reportUrl != null) {
        // 设置连接
        var fileUrl = `${this.reportData.reportUrl}`;
        GetStaticFileInfo(fileUrl, this.reportData.reportNum + ".docx");
        // var fileUrl = `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${this.reportData.reportUrl}`;
        // this.getBlob(fileUrl).then((blob) => {
        //   this.saveAs(blob, this.reportData.reportNum + ".docx");
        // });
      } else {
        const converted = htmlDocx.asBlob(this.reportData.reportFile);
        saverFile(converted, this.reportData.reportTemplateName + ".docx");
      }
    },

    // 通过文件下载url拿到对应的blob对象
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };

        xhr.send();
      });
    },
    // 下载文件js模拟点击a标签进行下载
    saveAs(blob, filename) {
      var link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    },

    // 关闭弹框
    handleClose() {
      this.$parent.getList();
      this.dialogVisible = false;
      this.$emit("update:dialogFormVisible", false);
    },
  },
};
</script>
<style lang="scss" scoped>
.chioseFileDiv {
  background-color: #f1f8ff;
  height: 45px;
  line-height: 45px;
}
</style>
